const app = getApp()
const config = require('../config/' + app.globalData.WX_ENV + '_config.js')

const getPageInstance = () => {
  let pages = getCurrentPages()
  return pages[pages.length - 1]
}
const getUrlParams = (params) => {
  if (params && Object.keys(params).length > 0) {
    return "?" + Object.keys(params).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    }).join("&");
  } else {
    return ''
  }
}

const getUrl = (url) => {
  if (url.indexOf('://') == -1) {
    url = config.API_PATH + url
  }
  return url
}
// 请求拦截器
const requestInterceptor = ({ url, params = {}, ...confs }, { loading = true, loadingText = '加载中' }) => {
  if (loading) {
    wx.showLoading({
      title: loadingText,
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    const RequestTask = wx.request({
      url: getUrl(url),
      data: params,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('Token') || '',
        'shopID': wx.getStorageSync('shopID') || 1
      },
      ...confs,
      complete: (res) => {
        if (loading) {
          wx.hideLoading()
        }
      },
      success: res => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          wx.showModal({
            title: '还没有登录！',
            content: '需要登录后才能继续操作！',
            confirmText: '立即登录',
            showCancel: false,
            success ({ confirm }) {
              if (confirm) {
                let currentInstance = getPageInstance()
                wx.redirectTo({
                  url: '/pages/Login/index?redirectUrl=' + encodeURIComponent(currentInstance.route + getUrlParams(currentInstance.options))
                })
              }
            }
          })
        } else {
          reject(new Error(res.data.Message))
        }
      },
      fail: res => {
        reject(new Error(res.errMsg))
      }
    })
  }).catch(e => {
    wx.showToast({
      icon: 'none',
      title: e.message
    })
  })
}

const _get = (url, params = {}, options = {}) => {
  return requestInterceptor({
    url,
    params,
    method: 'GET'
  }, options)
}

const _post = (url, params = {}, options = {}) => {
  return requestInterceptor({
    url,
    params,
    method: 'POST'
  }, options)
}

const _put = (url, params = {}, options = {}) => {
  return requestInterceptor({
    url,
    params,
    method: 'PUT'
  }, options)
}

const _delete = (url, params = {}, options = {}) => {
  return requestInterceptor({
    url,
    params,
    method: 'DELETE'
  }, options)
}

module.exports = {
  API_PATH: config.API_PATH,
  IMG_HOST: config.IMG_HOST,
  _get,
  _post,
  _put,
  _delete
}